<template>
	<div>
		<div class="field-line">
			<label>收货人</label>
			<input placeholder="请填写收货人姓名" v-model="address.receive_name">
		</div>
		<div class="field-line">
			<label>手机号码</label>
			<input placeholder="请填写收货人手机号码" type="number" max=11 v-model="address.receive_mobile">
		</div>
		<div class="field-line">
			<label>选择地区</label>
			<AddressSelector
			v-model="addressSeletor"></AddressSelector>
		</div>
		<div class="field-line">
			<label>详细地址</label>
			<input placeholder="请填写详细地址" v-model="address.receive_address">
		</div>
		<div class="field-line">
			<label>设为默认地址</label>
			<div class="fr">
				<Radio v-model="address.selected"></Radio>
			</div>
		</div>
		<div class="big-btn" :class="{disabled: !validated || ajaxing}" @click="save">保存地址</div>
	</div>
</template>
<script>
import { Indicator} from 'mint-ui'
import { mapGetters, mapActions } from 'vuex'
import Radio from '@/components/Radio'
import AddressSelector from '@/components/AddressSelector'
export default{
	name:'AddressEdit',
	async created(){
		const addressId = this.$route.params.addressId
		this.type = addressId == '0' ?  'add' : 'edit'

		// 编辑时初始化数据
		if(addressId) {
			Indicator.open()
			await this.getAddressList()
			Indicator.close()

			this.address = {...this.list.find(a => a.address_id == addressId)}
			this.address.selected = Boolean(this.address.selected)
			this.addressSeletor = {
				province: this.address.receive_province,
				city: this.address.receive_city,
				district: this.address.receive_area
			}
		}
	},
	data(){
		return {
			type: 'add',
			address: {
				address_id:'',
				receive_name: '',
				receive_mobile: '',
				receive_province: '',
				receive_city: '',
				receive_area: '',
				receive_address: '',
				selected: false
			},
			addressSeletor: {
				province: '',
				city: '',
				district: ''
			},
			ajaxing: false
		}
	},
	computed:{
		...mapGetters({
			list: 'address/list'
		}),
		validated(){
			if(!this.address.receive_name ||
				!this.address.receive_mobile ||
				this.address.receive_mobile.length !== 11 ||
				!this.address.receive_address) return false
			else return true
		}
	},
	methods:{
		...mapActions({
			getAddressList: 'address/getAddressList',
			edit: 'address/toEdit',
			add: 'address/toAdd'
		}),
		async save(){
			if(!this.validated || this.ajaxing) return
			this.address.receive_province = this.addressSeletor.province
			this.address.receive_city = this.addressSeletor.city
			this.address.receive_area = this.addressSeletor.district

			Indicator.open()
			this.ajaxing = true
			let success
			if(this.type === 'add') success = await this.add(this.address)
			else success = await this.edit(this.address)
			this.ajaxing = false
			if(success) this.$router.go(-1)
			Indicator.close()
		}
	},
	components: { Radio, AddressSelector }
}
</script>
<style lang='less' scoped>
.big-btn{
	margin: 1rem auto;
}
</style>